<?php

namespace Common\Logic;

/**
 * 客栈逻辑
 * @modify zhangzhen 2016-12-22 创建
 */
class SynLogic extends \Common\Controller\BaseController {
	/**
     * 处理RPC的数据
	 * @modify zhangzhen 2016-12-22  同步美住时添加集群号
     * @param  string   $name       客栈名
     * @param  integer   $cityId     城市id
     * @param  integer   $districtId 区id
     */
	public function synCommunityDetail($clientData) {
		$userId = getUserId();
		$hotelSynModel = D('HotelSyn');
		$hotelEntityModel = D('HotelEntity');
		foreach($clientData as $key => $oneData){
			if($oneData['status']<2){
				unset($clientData[$key]);
				continue;
			}
			$hotelJson = array(
				'id' => $oneData['id'],
				'name' => $oneData['name'],
				'no' => $oneData['no'],
				'batchno' => $oneData['batchno'],
			);		
			$hotelJson = json_encode($hotelJson);
			$clientData[$key]['hotelJson'] = $hotelJson;
			$hotelSynDetail = $hotelSynModel->getInfoByMasterId($oneData['id']);
            if($hotelSynDetail){
                if($hotelSynDetail['creator'] == $userId){
                    $hotelEntityDetail = $hotelEntityModel ->getInfo($hotelSynDetail['hotelentity_id']);
                    $clientData[$key]['hotelentity_id'] = $hotelSynDetail['hotelentity_id'];
                    $clientData[$key]['hotelentity_name'] = $hotelEntityDetail['name'];
                    $clientData[$key]['hotelsyn_id'] = $hotelSynDetail['id'];
                    $clientData[$key]['name'] = $oneData['name'];
                }else{
                    unset($clientData[$key]);
                }
                
            }
		}
		return $clientData;
	  }
    /**
     * 同步客栈逻辑
     * @modify zhangzhen 2016-12-22  同步美住时添加集群号
	 * @modify wenhui 2017-05-24  添加时区
     * @param  string   $name       客栈名
     * @param  integer   $cityId     城市id
     * @param  integer   $districtId 区id
     * @param  integer   $communityNo 集群号
     * @param  integer   $masterentityId  集群Id
     * @param  integer   $userId  用户id
     * @param  string   $universalTime  时区 默认 中国
     */
    public function addInfo($name, $cityId, $districtId, $communityNo, $masterentityId, $universalTime = '5', $userId = null) {
        $userId = !empty($userId) ? $userId : getUserId();
        $AdminLoginModel = D('AdminLogin');
        $adminLogin = $AdminLoginModel->getInfo($userId);
        $hasDealer = $adminLogin['status'];
        // 添加客栈
        $hotelEntityModel = D('HotelEntity');
        $hotelEntityModel->startTrans();
        $commit = true;
        $addResult = $hotelEntityModel->addInfo($name, $cityId, $districtId, $communityNo, 2, null, $universalTime);
        if (!$addResult) {
            $commit = false;
        }
        $hotelId = $addResult;
		//经销商所属客户添加客栈设为已过期
        if ($commit && $hasDealer == 4) {
            $addResult = $hotelEntityModel->setDate($hotelId, date("Y-m-d",strtotime("-1 day")));
            if (empty($addResult)) {
                $commit = false;
            }
        }  

		//添加同步记录
		if ($commit) {
            $hotelSynModel = D('HotelSyn');
            $addResult = $hotelSynModel->addInfo($hotelId,$communityNo,$masterentityId,$adminLogin['id']);
            if (empty($addResult)) {
                $commit = false;
            }
        }
		
        if($commit) {
            Vendor('phpRPC.phprpc_client');
            $client = new \PHPRPC_Client(C('MANAGE_SYN_URL'));
            $client->setEncryptMode(3);
            $sendData = array(
                'flag' => 'uclbrt',
                'time' => time(),
                'm_adminlogin_id' => $userId,
                'm_adminlogin_mobile' => $adminLogin['mobile'],
                'm_hotelentity_id' => $hotelId,
                'm_hotelentity_name' => $name,
                'q_communityentity_id' => $masterentityId,
            );
            $clientData = $client->notifyCommunitySynchronized($sendData);
            if (empty($clientData)) {
                $commit = false;
            }

        }

        // 添加客栈信息记录
        if ($commit) {
            $hotelInfoModel = D('HotelInfo');
            $addResult = $hotelInfoModel->addInfo($hotelId);
            if (empty($addResult)) {
                $commit = false;
            }
        }

        // 添加客栈-人记录
        if ($commit) {
            $adminHotelModel = D('AdminHotel');
            $addResult = $adminHotelModel->addInfo($hotelId, $userId, HOTEL_ROLE_OWNER);
            if (!$addResult) {
                $commit = false;
            }
        }

        // 添加系统预设数据
        if ($commit) {
            $resourceInfo = $this->getResource();

            $channelData = array();
            foreach ($resourceInfo['channel'] as $channel) {
                array_push($channelData,
                        array(
                    'hotelentity_id' => $hotelId,
                    'name' => $channel,
                    'type' => RESOURCE_NOTDELETABLE,
                    'status' => NOT_DELETE,
                ));
            }
            unset($channel);

            $payData = array();
            foreach ($resourceInfo['pay'] as $pay) {
                array_push($payData,
                        array(
                    'hotelentity_id' => $hotelId,
                    'name' => $pay,
                    'type' => RESOURCE_NOTDELETABLE,
                    'status' => NOT_DELETE,
                ));
            }
            unset($pay);

            if (!empty($channelData)) {
                $hotelChannelModel = D('HotelChannel');
                $addResult = $hotelChannelModel->addInfo($channelData);
                if (!$addResult) {
                    $commit = false;
                }
            }

            if ($commit && !empty($payData)) {
                $hotelPayModel = D('HotelPay');
                $addResult = $hotelPayModel->addInfo($payData);
                if (!$addResult) {
                    $commit = false;
                }
            }
        }

        //会员设置为共享时，添加会员信息
        if($commit){
            $vipInitModel = D('VipInit');
            $vipInitInfo = $vipInitModel->getInfoByAdmin($userId);
            if($vipInitInfo['share'] == '1'){
                $adminHotelInfos = $adminHotelModel->getInfosByAdmin($userId);
                $vipInfoModel = D('VipInfo');
                $vipInfos = $vipInfoModel->getInfoByHotel($adminHotelInfos[0]['hotelentity_id']);
                foreach ($vipInfos as $key => $vipInfo) {
                    $addResult = $vipInfoModel->addInfo($vipInfo['name'], $hotelId, $vipInfo['auto'], $vipInitInfo['level'], $vipInfo['levelrule'], $vipInitInfo['discount'], $vipInfo['discountrule']);
                    if (!$addResult) {
                        $commit = false;
                        break;
                    }
                }
                if ($commit) {
                    $vipUserModel = D('VipUser');
                    $vipUserInfoModel = D('VipUserInfo');
                    $vipUsers = $vipUserModel->getInfoByHotel($adminHotelInfos[0]['hotelentity_id']);
                    foreach ($vipUsers as $key => $vipUser) {
                        $addResult = $vipUserModel->addInfo($hotelId, $vipUser['vipinfo_id'], $vipUser['name'], $vipUser['mobile'], $vipUser['identity'], $vipUser['areacode']);
                        $vipUserInfo = $vipUserInfoModel->getInfoByUserId($vipUser['id']);
                        $addResult=$vipUserInfoModel->addInfo($addResult,$vipUserInfo['gender'],$vipUserInfo['birthday'],$vipUserInfo['nation'],$vipUserInfo['address'],$vipUserInfo['wechat'],$vipUserInfo['remark']);
                        if (!$addResult) {
                            $commit = false;
                            break;
                        }
                    }
                }
            }
        }

        if ($commit) {
            $hotelEntityModel->commit();
            if($hasDealer == 4){
                $dealerAdmin = D('DealerAdmin')->getInfoByUser($userId);
                $dealerLogin = D('DealerLogin')->getInfo($dealerAdmin['dealerlogin_id']);
                if ($dealerLogin['areacode'] == '86') {
                    $smsUtil = new \Org\Util\Sms();
                    $smsUtil->sendAddHotelToDealer($dealerLogin['mobile'], $adminLogin['name'], $adminLogin['mobile'], $name);
                } else {
                    $smsUtil = new \Org\Util\yunPian();
                    $smsUtil->sendAddHotelToDealer($dealerLogin['areacode'], $dealerLogin['mobile'], $adminLogin['name'], $adminLogin['mobile'], $name);
                }
            }
            return true;
        } else {
            $hotelEntityModel->rollback();
            returnJson(500, 508, 'error');
        }
    }
	/**
     * 同步客栈管理账号
     * @modify songanwei 2016-12-22
     * @param type $adminId   管理员ID
     * @param type $account 账号
     * @param type $accountName  账号名称
     */
    public function addSynSub($hotelId,$adminId, $account, $accountName,$masterentityId,$usercommunityId,$areacode = '86') {
        //查询管理客栈
        $adminHotelModel = D('AdminHotel');
        $adminHotels = $adminHotelModel->getInfosByAdmin($adminId);
        if (empty($adminHotels)) {
            returnJson(403, 202);
        }
		
        //获取客栈默认权限
        $hotelAuthorityModel = D('HotelAuthority');
        $defaultAuthoritys = $hotelAuthorityModel->getInfosByDefault();

        $adminAuthorityData = $adminHotelData = array();
        //检查账户是否已添加
        $adminLoginModel = D('AdminLogin');
        $adminLogin = $adminLoginModel->getInfoByMobile($account, $areacode);

        if ($adminLogin) {
            //检查用户是否已存在
            $result = $adminHotelModel->checkExistAdmin($adminLogin['id'], $hotelId);
            if ($result) {
                //账号已存在
                returnJson(403, 104);
            }
        }

        //开启事务处理
        $adminHotelModel->startTrans();
        $commit = true;

        //未注册用户
        if ($adminLogin) {
			$adminHotelData[] = array(
				'hotelentity_id' => $hotelId,
				'adminlogin_id' => $adminLogin['id'],
				'role' => 2
			);
			foreach ($defaultAuthoritys as $defaultAuthority) {
				$adminAuthorityData[] = array(
					'adminlogin_id' => $adminLogin['id'],
					'hotelentity_id' => $hotelId,
					'hotelauthority_id' => $defaultAuthority['id'],
					'creator' => getUserId()
				);
			}
			//添加同步关系表
			if($commit){
				$adminSynModel = D('AdminSyn');
				$result = $adminSynModel->addInfo($masterentityId,$adminLogin['id'],$usercommunityId,$hotelId);
				if ($result == false) {
					$commit = false;
				}
			}
        } else {
            $token = getRandomPassword();
            // 添加用户主表
            $result = $adminLoginId = $adminLoginModel->addInfo($account, hash('sha256', $token), $accountName, $areacode);
            if ($result == false) {
                $commit = false;
            }
            //添加用户从表
            $adminInfoModel = D('AdminInfo');
            if ($commit) {
                $result = $adminInfoModel->addInfo($adminLoginId);
                if ($result == false) {
                    $commit = false;
                }
            }
			//添加同步关系表
			if($commit){
				$adminSynModel = D('AdminSyn');
				$result = $adminSynModel->addInfo($masterentityId,$adminLoginId,$usercommunityId,$hotelId);
				if ($result == false) {
					$commit = false;
				}
			}
			$adminHotelData[] = array(
				'hotelentity_id' => $hotelId,
				'adminlogin_id' => $adminLoginId,
				'role' => 2
			);
			foreach ($defaultAuthoritys as $defaultAuthority) {
				$adminAuthorityData[] = array(
					'adminlogin_id' => $adminLoginId,
					'hotelentity_id' => $hotelId,
					'hotelauthority_id' => $defaultAuthority['id'],
					'creator' => getUserId()
				);
			}
            
        }
        //添加管理员客栈关系数据
        if ($commit && $adminHotelData) {
            $result = $adminHotelModel->addAll($adminHotelData);
            if ($result == false) {
                $commit = false;
            }
        }

        //添加管理员客栈默认权限
        $adminAuthorityModel = D('AdminAuthority');
        if ($commit && $adminAuthorityData) {
            $result = $adminAuthorityModel->addAll($adminAuthorityData);
            if ($result == false) {
                $commit = false;
            }
        }

        //事务提交
        if ($commit) {
            $adminHotelModel->commit();
            //发送短信通知
            if (!$adminLogin) {

                if ($areacode == '86') {
                    $sms = new \Org\Util\Sms();
                    $result = $sms->sendNotReg($account, $token);
                } else {
                    $sms = new \Org\Util\yunPian();
                    $result = $sms->sendNotReg($areacode, $account, $token);
                }
                if ($result == false) {
                    returnJson(403, 151);
                }
            }
        } else {
            $adminHotelModel->rollback();
            returnJson(500, 508);
        }
    }
	/**
     * 删除子账号
     * @modify zhangzhen 2016-12-23
	 * @param integer $hotelId  客栈ID
     * @param integer $adminId  客栈创建管理员ID
     * @param integer $userId  客栈管理员ID
     */
    public function deleteSub($hotelId, $adminId, $userId) {
        //检查管理账号权限
        $adminHotelModel = D('AdminHotel');
        $adminHotels = $adminHotelModel->getInfosByAdmin($adminId);
        if (empty($adminHotels)) {
            returnJson(403, 324);
        }
		//是否在账号管理页面已经删除该管理员
		$existAdmin = $adminHotelModel->getInfoByAdminHotel($adminId,$hotelId);
		if($existAdmin){
			$adminHotelModel->startTrans();
			$commit = true;
			//删除管理客栈关系
			$result = $adminHotelModel->deleteInfoAdminHotel($userId, $hotelId);
			if ($result == false) {
				$commit = false;
			}

			// 删除子管理员的对应客栈房间权限
			if ($commit) {
				$hotelRoomAuthorityModel = D('HotelRoomAuthority');
				$result = $hotelRoomAuthorityModel->deleteInfoByHotel($userId, $hotelId);
				if (empty($result)) {
					$commit = false;
				}
			}
			if ($commit) {
				//删除管理客栈权限数据
				$adminAuthorityModel = D('AdminAuthority');
				$result = $adminAuthorityModel->deleteInfoByAdminHotel($userId, $hotelId);
				if ($result == false) {
					$commit = false;
				}
			}
			if ($commit) {
				//删除同步表数据
				$adminSynModel = D('AdminSyn');
				$temp = $adminSynModel->deleteInfoByAdminHotel($userId, $hotelId);
				if ($result == false) {
					$commit = false;
				}
			}
			if ($commit) {
				$adminHotelModel->commit();
			} else {
				$adminHotelModel->rollback();
				returnJson(500, 510);
			}
		}else{
			$adminSynModel = D('AdminSyn');
			$result = $adminSynModel->deleteInfoByAdminHotel($userId, $hotelId);
		}
    }
	/**
     * 同步房型与房间
     * @modify zhangzhen 2016-12-28    创建
     * @modify wenhui 2017-09-14    新增字段 $charityPrice
     */
	public function addSynRoomTypeAndRooms($hotelId, $roomTypeName, $roomTypePrice, $roomInfos, $charityPrice = null){
		$roomTypeModel = D('RoomType');
        $roomTypeModel->startTrans();
        $commit = true;

        // 添加房型
        $addResult = $roomTypeModel->addInfo($hotelId, $roomTypeName, $roomTypePrice, $charityPrice);
        if (empty($addResult)) {
            $commit = false;
        }

        // 添加房间
        if ($commit && !empty($roomInfos)) {
			$roomInfoModel = D('RoomInfo');
			$roomSynModel = D('RoomSyn');
			$roomTypeId = $addResult;
			for($i = 0; $i < count($roomInfos); $i++){
				$roomInfo = explode(',',$roomInfos[$i]);
				//$roomInfo[0] = $communityentity_id,
				//$roomInfo[1] = $builderinfo_id,
				//$roomInfo[2] = $floorinfo_id,
				//$roomInfo[3] = $masterroominfo_id,
				//$roomInfo[4] = $roomName,
                //$roomInfo[5] = $locktype,
				$roomData['name'] = $roomInfo[4];
				$roomData['roomfrom'] = $roomInfo[5];
				$addResult = $roomInfoModel->addSynInfo($hotelId, $roomTypeId, $roomData);
				$roomSynModel->addInfo($roomInfo[0], $roomInfo[1], $roomInfo[2], $roomInfo[3], $hotelId, $addResult);
			}
            if (empty($addResult)) {
                $commit = false;
            }
        }

        if ($commit) {
            $roomTypeModel->commit();
            return true;
        } else {
            $roomTypeModel->rollback();
            returnJson(200, 508, 'error');
        }
	}
	/**
     * 同步房间
     * @modify zhangzhen 2016-12-27    创建
     */
	public function addSynRooms($hotelId,$roomTypeId,$roomInfos){
		$roomInfoModel = D('RoomInfo');
		$roomSynModel = D('RoomSyn');
		for($i = 0; $i < count($roomInfos); $i++){
            $roomInfo = explode(',',$roomInfos[$i]);
			//$roomInfo[0] = $communityentity_id,
			//$roomInfo[1] = $builderinfo_id,
			//$roomInfo[2] = $floorinfo_id,
			//$roomInfo[3] = $masterroominfo_id,
			//$roomInfo[4] = $roomName,
            //$roomInfo[5] = $locktype,
			$roomData['name'] = $roomInfo[4];
			$roomData['roomfrom'] = $roomInfo[5];
			$addResult = $roomInfoModel->addSynInfo($hotelId, $roomTypeId, $roomData);
			$roomSynModel->addInfo($roomInfo[0], $roomInfo[1], $roomInfo[2], $roomInfo[3], $hotelId, $addResult);
        }
	}
	/**
     * 获取同步房间
     * @modify zhangzhen 2016-12-27    创建
     */
	public function getSynRoom($hotelId){
		//获取房型
		$roomTypeModel = D('RoomType');
		$roomInfoModel = D('RoomInfo');
		$roomType = $roomTypeModel->getInfoByHotel($hotelId);
		foreach($roomType as $key => $oneRoomType){
			$roomInfoDetail = $roomInfoModel->getInfoByRoomTypeAndRoomFrom($hotelId ,$oneRoomType['id'] ,[1,2,3,5]);
			$roomType[$key]['room'] = $roomInfoDetail;
		}
		return $roomType;
	}
	/**
     * 获取同步房间
     * @modify zhangzhen 2016-12-27    创建
     */
	public function getImportRoom($hotelId, $rooms){
		//获取房型
		$roomInfoModel = D('RoomInfo');
		foreach($rooms as $key => $room){
			$result = $roomInfoModel->getInfoByName($hotelId,$room['no']);
			if($result || $room['locktype'] == 4){
				unset($rooms[$key]);
				continue;
			}
			$roomFormat[$room['floorinfo_id']][] = $room;
			$room['buildName'] = $room['buildName'] ? $room['buildName'] : '未填楼栋';
			$room['floorName'] = $room['floorName'] ? $room['floorName'] : '未填楼层';
			$roomFormat[$room['floorinfo_id']][0]['buildFloorName'] = $room['buildName'] .' - '. $room['floorName'];
		}
		return $roomFormat;
	}
	/**
     * 获取index页面的同步信息
     * @modify zhangzhen 2016-12-27    创建
     */
	public function getHotelSynDetail(){
		$userId = getUserId();
		$hotelSynModel = D('HotelSyn');
		//获取集群ID
		$hotelSynDetail = $hotelSynModel->getInfoByUserId($userId);
		foreach($hotelSynDetail as $oneHotelSyn){
			$communityIds[] = $oneHotelSyn['masterentity_id'];
			$hotelIds[] = $oneHotelSyn['hotelentity_id'];
		}
		$communityIds = implode(',',$communityIds);
		$hotelIds = implode(',',$hotelIds);
		Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('MANAGE_SYN_URL'));
        $client->setEncryptMode(3);
        $sendData = array(
            'flag' => 'uclbrt',
            'time' => time(),
            'communityIds' => $communityIds,
        );
		$clientData = $client->getCommunityInfo($sendData);
		//判断是否为二维数组
		if((count($clientData) == count($clientData,1))){
			$clientData[] = $clientData;
		}
		//组合集群名字
		foreach($hotelSynDetail as $key => $oneHotelSyn){
			foreach($clientData as $oneData){
				if($oneHotelSyn['masterentity_id'] == $oneData['id'])
					$hotelSynDetail[$key]['communityName'] = $oneData['name'];
			}
		}
		$hotelEntityModel = D('HotelEntity');
		$hotelEntityDetail = $hotelEntityModel->getInfo($hotelIds);
		//判断是否为二维数组
		if((count($hotelEntityDetail) == count($hotelEntityDetail,1))){
			$hotelEntityDetail[] = $hotelEntityDetail;
		}
		
		//组合客栈名字
		foreach($hotelSynDetail as $key => $oneHotelSyn){
			foreach($hotelEntityDetail as $oneHotelEntity){
				if($oneHotelSyn['hotelentity_id'] == $oneHotelEntity['id'])
					$hotelSynDetail[$key]['hotelName'] = $oneHotelEntity['name'];
					
			}
		}
		return $hotelSynDetail;
	}
	/**
     * 删除同步房间
     * @modify zhangzhen 2016-12-27    创建
     */
	public function deleteSynRoom($hotelId, $roomId){
		$orderRoomModel = D('OrderRoom');

        // 检查房间是否有活跃状态订单
        $orderInfo = $orderRoomModel->getInfoByHotelRoom($hotelId, $roomId);
        // 无效订单无法阻止房间删除
        foreach ($orderInfo as $index => $orderItem) {
            if (in_array($orderItem['status'], array(ORDER_CHECKOUTED, ORDER_CANCELED, ORDER_OUTDATED))) {
                unset($orderInfo[$index]);
            }
        }
        unset($orderItem);
        if(!empty($orderInfo)) {
            returnJson(403, 300, 'error');
        }
		$roomInfoModel = D('RoomInfo');
		$result = $roomInfoModel->deleteInfo($roomId);
		if(!$result){
			returnJson(403, 202);
		}
		
		$roomSynModel = D('RoomSyn');
		$roomSynModel->deleteInfo($roomId);
		
	}
	/**
     * 获取系统默认客栈资源
     * @modify trainyao 2016-01-09    创建
     */
    public function getResource() {
        return $this->__singleGet('_getResource');
    }
    protected function _getResource() {
        $return = array();
        $channelModel = D('Channel');
        $return['channel'] = $channelModel->getInfo();
        $return['channel'] = array_column($return['channel'], 'name');

        $payModel = D('Pay');
        $return['pay'] = $payModel->getInfo();
        $return['pay'] = array_column($return['pay'], 'name');

        return $return;
    }
}
